package pt.fct.mpc.lastfm.connectivity;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;

import pt.fct.mpc.lastfm.connectivity.bt.LastfmBluetoothException;
import pt.fct.mpc.lastfm.connectivity.bt.LastfmBluetoothGateway;
import pt.fct.mpc.lastfm.connectivity.bt.LastfmBluetoothManager;
import android.util.Log;

public class LastfmURL
{
	private static final String TAG = "Last.fm URL";
	private URL url;
	
	public LastfmURL(String url_str) 
		throws MalformedURLException
	{
		this.url = new URL(url_str);
	}

	public String toExternalForm()
	{
		return this.url.toExternalForm();
	}

	public InputStream openStream() 
		throws IOException, LastfmBluetoothUnavailableException
	{
		InputStream is = null;
		boolean active_bt = false;
		boolean use_bt = LastfmBluetoothManager.useBluetooth();
		
		Log.d(TAG, "openStream() begins");
		if (use_bt)
		{
			Log.d(TAG, "Using gateway-over-bluetooth connection");

			active_bt = LastfmBluetoothManager.isOn();
			
			if (!active_bt)
				throw new LastfmBluetoothUnavailableException("Unable to use bluetooth");

			LastfmBluetoothManager bt_manager;
			LastfmBluetoothGateway bt_gateway;

			try
			{
				bt_manager = LastfmBluetoothManager.getInstance();
				bt_gateway = bt_manager.getGateway();

				bt_gateway.beginConnection();

			} catch (LastfmBluetoothException e)
			{
				e.printStackTrace();
				throw new IOException(e.getMessage());
			}

			Log.d(TAG, "Acquiring BT I/O streams");

			OutputStream out;
			InputStream in;

			out = bt_gateway.getOutputStream();
			in = bt_gateway.getInputStream();
				
			if ((out == null) || (in == null))
				throw new IOException("Unavailable streams");

			Log.d(TAG, "Opening streams to Gateway");
			BufferedWriter writer = 
				new BufferedWriter(new OutputStreamWriter(out));

			Log.d(TAG, "Writing URL to output writer stream");
			writer.write(this.url.toExternalForm());
			writer.newLine();
			Log.d(TAG, "Flushing output writer stream");
			writer.flush();

			is = in;
		}
		
		if (active_bt == false)
		{
			Log.d(TAG, "Opening regular stream.");
			is = this.url.openStream();
		}
		
		Log.d(TAG, "openStream() ends; is = "+is);
		
		return is;
	}

	public void finished()
	{
		boolean use_bt = LastfmBluetoothManager.useBluetooth();
		if (use_bt)
			return;
		
		LastfmBluetoothManager bt_manager;
		LastfmBluetoothGateway bt_gateway;
		try
		{
			bt_manager = LastfmBluetoothManager.getInstance();
			bt_gateway = bt_manager.getGateway();
			
			if (bt_gateway != null)
				bt_gateway.endConnection();
			
		} catch (LastfmBluetoothException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

}
